/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tubes1sister.tracker;

import tubes1sister.tools.Timer;
import tubes1sister.tools.Event;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import tubes1sister.tools.dbconnector;

/**
 *
 * @author Muhammad Anis
 */
class TrackerHandler implements Runnable {

    Socket server;
    //pesan yang ditangkap dari client
    private URL request;
    String message;
    Timer timer;
    public boolean isTimeout = false;

    TrackerHandler(Socket server) {
        this.server = server;
    }

    public void run() {
        try {
            boolean update = false;
            message = "";
            String answer = "";
            HashMap<String, String> query = new HashMap<String, String>();
            //dapatkan input dari client
            DataInputStream in = new DataInputStream(server.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            PrintWriter out = new PrintWriter(new OutputStreamWriter(server.getOutputStream()));
            InetAddress addr = server.getInetAddress();
            //System.out.println("alamat : "+addr.getHostAddress());
            timer = new Timer(10000,"TrackerHandler");
            timer.start();
            timer.reset();
            do {
                System.out.println("Start");
                while ((message = br.readLine()) != null) {
                    request = new URL(message);
                    System.out.println("Pesan Diterima dari client: " + message);
                    request = new URL(message);
                    System.out.println(request.toURI());
                    System.out.println("Query: " + request.getQuery());
                    query = parseQuery(request.getQuery());
                    //kirim balasan ke client
                    if (!isFinished(query)) {
                        //System.out.println("masuk sini ga?");
                        TrackerResponse tr = new TrackerResponse();
                        tr.getResponseFromFile(query.get("info_hash"));
                        int interval = tr.interval;
                       
                        answer = tr.makeResponse();
                        System.out.println("jawaban: " + answer);
                        if (update == false) {
                            Connection conn = null;
                            try {
                                conn = DriverManager.getConnection(dbconnector.tempatconnect, dbconnector.username,dbconnector.password);

                                //System.out.println("di sini");
                                java.sql.Statement stmt = null;
                                ResultSet rs = null;
                                stmt = conn.createStatement();
                                String tempip = server.getInetAddress().toString().substring(1);
                                String sqlQuery = "INSERT INTO tubes (filename,ip,port) VALUES ('"+ query.get("info_hash") +"', '"+ tempip +"', '"+query.get("port")+"')";
                                int a = stmt.executeUpdate(sqlQuery);
                                update = true;
                            } catch (Exception e) {
                                System.out.println("masuk exception");
                            }
                        }
                        out.println(answer);
                        out.flush();
                        timer = new Timer(interval);
                        timer.start();
                        timer.reset();

                    } else {
                        break;
                    }
                }
                try{
                    int a = Integer.parseInt(query.get("event"));
                }catch(Exception e){
                    break;
                }
            } while (!(Integer.parseInt(query.get("event")) == Event.COMPLETED || Integer.parseInt(query.get("event")) == Event.STOPPED) && !timer.isTimeOut);
            //kalo sudah selesai kirim data bahwa sudah selesai
            //System.out.println("Menutup Koneksi");
            out.println(Event.DROP_CONNECTION);
            out.flush();
            out.close();
            br.close();
            in.close();
            //timer.stop();
            TrackerServer.currentConnection--;
        } catch (Exception ex) {
            Logger.getLogger(TrackerHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public HashMap<String, String> parseQuery(String query) {
        HashMap<String, String> temp = new HashMap<String, String>();
        //parsing query berdasarkan simbol &&
        String[] parameterName = query.split("&&");
        //System.out.println("Panjang parameter: " + parameterName.length);
        for (int i = 0; i < parameterName.length; i++) {
            //split berdasarkan =, lalu masukkan ke dictionary
            //System.out.println("paramater: " + i + "  " +parameterName[i]);
            String[] ret = parameterName[i].split("=");
            //System.out.println("Panjang parameter: " + ret[1]);
            temp.put(ret[0], ret[1]);
        }
        //System.out.println("Panjang hasil: " + temp.size());
        return temp;
    }

    public boolean isFinished(HashMap<String, String> query) {
        String temp1 = query.get("event");
        return (Integer.parseInt(temp1) == Event.COMPLETED || Integer.parseInt(temp1) == Event.STOPPED);
    }
}
